package cn.tedu.ivos.audit.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.dto.ApplicationQuery;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.application.pojo.vo.ApplicationVO;
import cn.tedu.ivos.application.sevice.ApplicationService;
import cn.tedu.ivos.application.sevice.impl.ApplicationServiceImpl;
import cn.tedu.ivos.audit.mapper.AuditMapper;
import cn.tedu.ivos.audit.pojo.dto.AuditQuery;
import cn.tedu.ivos.audit.pojo.dto.AuditSaveParam;
import cn.tedu.ivos.audit.pojo.entity.Audit;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.base.enums.AuditStatusEnum;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Transactional
@Slf4j
@Service
public class AuditServiceImpl implements AuditService {
    @Autowired
    private AuditMapper auditMapper;
    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public void insertAudit(Application application) {
        log.debug("为申请单生成审批单业务，参数：{}", application);
        //1.获取审批人id集合
        List<Long> userIdList = application.getAuditUserIdList();
        //2.遍历id集合
        for (int i = 0; i < userIdList.size(); i++) {
            //3.有几个审批人id就有几个审批单
            Audit audit = new Audit();
            //4.1设置申请单id
            audit.setApplicationId(application.getId());
            //4.2设置审批人id
            audit.setAuditUserId(userIdList.get(i));
            //4.3设置审批次序
            audit.setAuditSort(i);
            //4.4设置审批状态
            if (i == 0){
                audit.setAuditStatus(AuditStatusEnum.MY_PENGDING.getCode());
            }else {
                audit.setAuditStatus(AuditStatusEnum.PENGDING.getCode());
            }
            //4.5设置创建时间
            audit.setCreateTime(new Date());
            //5.将审批单保存到数据库中
            log.debug("为申请单生成审批单业务，即将保存审批单：{}", audit);
            auditMapper.insert(audit);
        }
    }

    @Override
    public List<AuditVO> selectAuditByApplicationId(Long id) {
        return auditMapper.selectAuditByApplicationId(id);
    }

    @Override
    public void deletAudit(Long applicationId) {
        log.debug("删除审批单业务，参数：{}", applicationId);
        auditMapper.deleteAudit(applicationId);
    }

    @Override
    public List<AuditVO> selectAudit(AuditQuery auditQuery) {
        log.debug("查询审批单业务，参数：{}", auditQuery);
//        Audit audit = new Audit();
//        BeanUtils.copyProperties(auditQuery, audit);
        List<AuditVO>  list = auditMapper.selectAudit(auditQuery);
        log.debug("查询审批单业务，查询结果1：{}", list);
        for (int i = 0; i < list.size(); i++) {
            AuditVO auditVO = list.get(i);
            assignAuditUserList(auditVO);
        }
        //返回查询结果
        return list;
    }

    @Override
    public void updateAudit(AuditSaveParam auditSaveParam) {
        log.debug("更新审批业务，参数：{}", auditSaveParam);
        Audit audit = new Audit();
        BeanUtils.copyProperties(auditSaveParam, audit);
        audit.setUpdateTime(new Date());
        //更新当前的这个审批单,审批单的状态是30还是40是由前端传过来的
        auditMapper.update(audit);
        //准备更新此审批单对应的申请单
        Application application = new Application();
        application.setId(audit.getApplicationId());
        application.setUpdateTime(new Date());
        /* 判断是通过处理还是驳回处理 */
        if(audit.getAuditStatus().equals(AuditStatusEnum.AUDITED.getCode())){//通过处理
            //1.继续查当前审批单对应的其它审批单(与当前审批单批同一个申请单)
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            //2.根据申请单id,查出此申请单对应的所有未审批的审批单总数
            Integer count = auditMapper.selectRestAuditCount(auditQuery);
            if(count>0){
                //还有未审批的审批单
                //3.根据申请单id与审批次序+1找到下一条未审批的审批单
                auditQuery.setAuditSort(audit.getAuditSort()+1);
                List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
                if(auditVOList != null && auditVOList.size()>0){
                    AuditVO auditVO = auditVOList.get(0);
                    //4.准备更新第2条审批单
                    Audit Audit2 = new Audit();
                    Audit2.setId(auditVO.getId());
                    Audit2.setAuditStatus(AuditStatusEnum.MY_PENGDING.getCode());
                    Audit2.setUpdateTime(new Date());
                    auditMapper.update(Audit2);
                }
                //5.更新申请单
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.cancelById(application);
            }else{
                //刚刚更新的审批单是最后一个审批单了
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.cancelById(application);
            }
        }else if (audit.getAuditStatus().equals(AuditStatusEnum.REJECT.getCode())){//驳回处理
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
            if (auditVOList != null && auditVOList.size() > 0) {
                for (int i = 0; i < auditVOList.size(); i++) {
                    AuditVO auditVO = auditVOList.get(i);
                    if(auditVO.getAuditStatus().equals(AuditStatusEnum.PENGDING.getCode())){
                        auditMapper.deleteById(auditVO.getId());
                    }
                }
            }
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(auditSaveParam.getRejectReason());
            applicationMapper.cancelById(application);
        }
    }

    private void assignAuditUserList(AuditVO auditVO) {
        //1.准备空集合,分别用来保存审批人id与姓名
        List<Long> auditUserIdList = new ArrayList<>();
        List<String> auditUsernameList = new ArrayList<>();
        //2.根据传入的申请单对象,获取其id,查出此申请单对应的审批单
        List<AuditVO> auditVOList = auditMapper.selectAuditByApplicationId(auditVO.getApplicationId());
        //3.依次遍历取出每一个审批单对象
        for(int i = 0; i < auditVOList.size(); i++){
            //4.获取当前审批单的审批人数据
            Long userId = auditVOList.get(i).getAuditUserId();
            auditUserIdList.add(userId);
            //5.获取当前审批人的姓名
            UserVO userVO = userMapper.selectById(userId);
            auditUsernameList.add(userVO.getUsername());
        }
        //6.准备一个拼接工具,将多个审批人姓名连成一个字符串
        StringJoiner stringJoiner = new StringJoiner(",");
        for(String username : auditUsernameList){
            stringJoiner.add(username);
        }
        //7.将准备好的数据赋值给传入的auditVO
        auditVO.setAuditUserIdList(auditUserIdList);
        auditVO.setAuditUsernameList(stringJoiner.toString());
    }
}
